package cn.wolfcode.crm.web.interceptor;

import cn.wolfcode.crm.domain.Employee;
import cn.wolfcode.crm.util.RequiredPermission;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

//自定义拦截器
public class SecurityInterceptor implements HandlerInterceptor {
    //对请求做预处理
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Employee e = (Employee) request.getSession().getAttribute("EMPLOYEE_IN_SESSION");
        //超管直接放行
        if(e.isAdmin()){
            return true;
        }

        //如果访问的方法不需要权限，放行
        HandlerMethod hm = (HandlerMethod) handler;
        //当前访问的方法对象
        Method method = hm.getMethod();

        if(!method.isAnnotationPresent(RequiredPermission.class)){
            return true;
        }

        //检查当前用户是否拥有访问的方法需要的权限
        List<String> expressions = (List<String>) request.getSession().getAttribute("EXPRESSIONS_IN_SESSION");


        //获取当前访问方法需要的权限表达式
        RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
        String expression = annotation.expression();

        if(expressions.contains(expression)){
            return true;
        }
        //请求转发到错误页面
        request.getRequestDispatcher("/WEB-INF/views/common/nopermission.jsp").forward(request,response);
        return false;//拦截
    }

    //对响应做预处理
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    //对处理完成之后的处理
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
